// 配置文件上传axios
import axios from 'axios'
import { ElMessage } from 'element-plus'
const devBaseURL = "/file"
const proBaseURL = "http://127.0.0.1:8081"
const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseURL : proBaseURL

import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false })

const upload = axios.create({
    baseURL: BASE_URL,
    timeout: 5000,
    headers: { 'Content-Type': 'multipart/form-data' },
    withCredentials: true
})

upload.interceptors.request.use(
    // 请求拦截
    (config) => {
        // 1.发送网络请求时, 在界面的中间位置显示Loading的组件
        NProgress.start(); // 启动滚动条
        // 2.某一些请求要求用户必须携带token, 如果没有携带, 那么直接跳转到登录页面
        if (sessionStorage.getItem('token')) {
            config.headers.authorization = sessionStorage.getItem('token')
        }
        // 3.params/data序列化的操作
        return config
    },
    () => { }
)

upload.interceptors.response.use(
    // 响应拦截
    (res) => {
        NProgress.done()// 关闭滚动条
        return res.data
    },
    (err) => {
        console.log(err.response)
        if (err && err.response) {
            switch (err.response.status) {
                case 401:
                    ElMessage.error(err.response.data.msg)
                    sessionStorage.removeItem('token')
                    router.replace({
                        path: '/login',
                        query: { redirect: router.currentRoute.fullPath }
                    })
                    break
                default:
                    ElMessage.error(err.response.data.msg)
            }
        }
        return err
    }
)


export const uploadImg = (file) => {
    let data = new FormData()
    data.append('file', file)
    // data.append('file', file) 添加其他数据
    return upload({
        url: '/upload',
        method: 'POST',
        data
    })
}

